#!/usr/bin/python3
# @Time    : 2024-03-22 上午 9:34
# @Author  : MingYangHe
# @Email   : 1780040868@qq.com
"""
deleteAtIndex(index)：如果索引 index 有效，则删除链表中的第 index 个节点
"""


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def getValue(self):
        return self.val

    def getNextValue(self):
        return self.next

    def setValue(self, new_val):
        self.val = new_val

    def setNextValue(self, new_next):
        self.next = new_next


class MyLinkedList:
    def __init__(self):
        self.dummy_head = ListNode()
        self.size = 0

    def get(self, index: int) -> int:
        """get(index)：获取链表中第 index 个节点的值。如果索引无效，则返回-1。"""
        if index < 0 or index >= self.size:
            return -1
        current = self.dummy_head.next
        for i in range(index):
            current = current.next
        return current.val

    def addAtHead(self, val: int) -> None:
        """addAtHead(val)：在链表的第一个元素之前添加一个值为 val 的节点。插入后，新节点将成为链表的第一个节点。"""
        self.dummy_head.next = ListNode(val, self.dummy_head.next)
        self.size += 1

    def addAtTail(self, val: int) -> None:
        """addAtTail(val)：将值为 val 的节点追加到链表的最后一个元素。"""
        current = self.dummy_head
        while current.next:
            current = current.next
        current.next = ListNode(val)
        self.size += 1

    def addAtIndex(self, index: int, val: int) -> None:
        """addAtIndex(index,val)：在链表中的第 index 个节点之前添加值为 val  的节点。
        如果 index 等于链表的长度，则该节点将附加到链表的末尾。
        如果 index 大于链表长度，则不会插入节点。
        如果index小于0，则在头部插入节点。"""
        if index > self.size:
            return
        elif index < 0:
            self.addAtHead(val)
        else:
            current = self.dummy_head
            for i in range(index):
                current = current.next
            current.next = ListNode(val, current.next)
            self.size += 1

    def deleteAtIndex(self, index: int) -> None:
        if index < 0 or index >= self.size:
            return

        current = self.dummy_head
        for i in range(index):
            current = current.next
        current.next = current.next.next
        self.size -= 1

    def printList(self):
        current = self.dummy_head.next
        while current:
            print(current.getValue(), end=" -> ")
            current = current.getNextValue()
        print("None")


# Your MyLinkedList object will be instantiated and called as such:
myLinkedList = MyLinkedList()
myLinkedList.printList()

myLinkedList.addAtHead(1)
myLinkedList.printList()

myLinkedList.addAtTail(3)
myLinkedList.printList()

myLinkedList.addAtIndex(1, 2)  # 链表变为 1->2->3
myLinkedList.printList()

print(myLinkedList.get(1))  # 返回 2

myLinkedList.deleteAtIndex(1)  # 现在，链表变为 1->3
myLinkedList.printList()

print(myLinkedList.get(1))  # 返回 3
